package com.lebang.schedule;

import com.lebang.component.MultiwordComponent;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.domain.TaskRouseDetail;
import com.lebang.entity.task.LbbCommon;
import com.lebang.entity.task.LbbSosoWithBLOBs;
import com.lebang.entity.task.TaskComments;
import com.lebang.example.TaskRouseDetailExample;
import com.lebang.mapper.LbbCommonMapper;
import com.lebang.mapper.LbbSosoMapper;
import com.lebang.mapper.TaskCommentsMapper;
import com.lebang.mapper.TaskRouseDetailMapper;
import com.lebang.model.TaskInitModel;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.service.CpaService;
import com.lebang.service.DownAppService;
import com.lebang.service.TaskRouseDetailService;
import com.lebang.service.task.TaskService;
import com.lebangweb.common.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.lebang.common.validcode.ValidCodeUtil.U_MENT_PHONE_CODE;
import static com.lebang.controller.api.SdkUploadApi.ON_SDK_MEMBER;
import static com.lebang.schedule.SdkReloadTask.SDK_QUEQUE;
import static com.lebang.service.CpaService.ZY_ROUSE_DETAIL;
import static com.lebang.service.TaskInRedisService.HASH_CSJ;

@Component
public class MultiwordTask {
    private static final Logger log = LoggerFactory.getLogger(MultiwordTask.class);

    @Autowired
    @Qualifier("multiwordservice")
    private TaskService<LbbCommon> multiwordService;
    @Autowired
    private MultiwordComponent multiwordComponent;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private LbbCommonMapper lbbCommonMapper;
    @Autowired
    private LbbSosoMapper lbbSosoMapper;

    @Autowired
    @Qualifier(value = "commonTaskService")
    private TaskService<LbbCommon> commonService;
    @Autowired
    private TaskService<LbbSosoWithBLOBs> sosoService;
    @Autowired
    private TaskService<TaskComments> commentsTaskService;
    @Autowired
    private TaskCommentsMapper taskCommentsMapper;
    @Autowired
    private TaskRouseDetailMapper taskRouseDetailMapper;
    @Autowired
    private RedisSdkClient sdkClient;
    @Autowired
    private TaskRouseDetailService taskRouseDetailService;
    @Autowired
    private CpaService cpaService;
    @Autowired
    private DownAppService downAppService;
    @Value("${spring.application.name}")
    private String appName;
    /**
     * 每天凌晨23:59:50清空当天量并且获取当日量
     */
    @Scheduled(cron = "50 59 23 * * ?")
    public void execute() {
        if(!"new-net-earns".equals(appName)){
            return;
        }
        //获取时间保证每日的启动时间为当天 有时候处理延迟,待提交和待审核能获取到
        LocalDateTime dateTime=LocalDateTime.now().minusHours(5);
        String str = UUIDUtil.M();
        // 此处加锁5分钟保证执行计划只有一个系统执行其他系统不执行
        boolean lock = redisClient.tryGetDistributedLock("multiwordtask", str, 10000);
        if (lock) {

            try {

                log.info("开始执行每日任务...");
                log.info("读取当天每日量...");
                //multiwordComponent.updatetodaytotal();
                lbbCommonMapper.updatetodaytotal();
                //lbbSosoMapper.updatetodaytotal();
                taskCommentsMapper.updatetodaytotal();
                //taskRouseDetailMapper.updatetodaytotal();
                commentsTaskService.starTaskAmount(dateTime);
                //multiwordService.starTaskAmount(dateTime);
                commonService.starTaskAmount(dateTime);
                //sosoService.starTaskAmount(dateTime);
                log.info("清空当天每日次数...");


                log.info("开始加载微信一元提现邀请码");
            } catch (Exception e) {
                e.printStackTrace();
                redisClient.releaseDistributedLock("multiwordtask", str);
            }
        } else {
            log.info("其他应用已执行过了...");
        }
        sdkClient.del(ON_SDK_MEMBER,SDK_QUEQUE);
    }


    /**
     * 清空当日短信的发送次数
     */
    @Scheduled(cron = "50 59 23 * * ?")
    public void clean(){
        String str = UUIDUtil.M();
        // 此处加锁5分钟保证执行计划只有一个系统执行其他系统不执行
        boolean lock = redisClient.tryGetDistributedLock("cleantask", str, 10000);
        if (lock) {
            taskRouseDetailMapper.updatetodaytotal();
            log.info("重置用户短信发送次数和穿山甲今日看视频统计...");
            redisClient.del(U_MENT_PHONE_CODE,HASH_CSJ);
        }else{
            log.info("其他应用已执行过了...");
        }

    }


    /**
     * 每日凌晨0点01分重载自营任务的任务池
     */
    @Scheduled(cron = "0 1 0 * * ?")
    public void executeReload() {

        String str = UUIDUtil.M();
        // 此处加锁5分钟保证执行计划只有一个系统执行其他系统不执行
        boolean lock = redisClient.tryGetDistributedLock("ZY_POOL_RELOAD", str, 100000);
        if (!lock) {
            log.info("其他应用已执行过了...");
            return;
        }
        try{
            redisClient.del(ZY_ROUSE_DETAIL);
            TaskRouseDetailExample example = new TaskRouseDetailExample();
            example.createCriteria().andRouseIdEqualTo(3L).andEnableEqualTo(1).andHasDeletedEqualTo(0);
            //所有上架的自营任务
            List<TaskRouseDetail> taskRouseDetails = taskRouseDetailService.selectByExample(example);
            taskRouseDetails.forEach(s->{
                int success = downAppService.getByStatus(s.getId(), DownStatus.SUCCESS.getIndex(),cpaService.getZyData() );
                int f = downAppService.getByStatus(s.getId(), DownStatus.RELSE.getIndex(),cpaService.getZyData() );
                s.setSuccessCount(success);
                s.setFailCount(f);
                taskRouseDetailService.updateById(s);
                TaskInitModel model=new TaskInitModel();
                model.setId(s.getId());
                model.setAmount(s.getDayAmount());
                model.setSuccessTotal(s.getSuccessCount());
                model.setTodayTotal(s.getTodaySuccessCount());
                model.setTotal(s.getRecordCount());
                cpaService.taskInitByTaskModel(model);
            });

            log.info("自营任务重载完成");
        }catch(Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
        }

    }


}
